import { cloneDeep } from 'lodash-es';
//向上移动
export function up(index, arr) {
  if (index == 0) {
    //开头不移动
    return;
  }
  const curObj = arr[index]; //当前对象
  const preObj = arr[index - 1]; //上一个对象
  arr.splice(index, 1, preObj); //上一个对象移动到当前对象
  arr.splice(index - 1, 1, curObj); //当前对象往上移动
  return arr;
}
//向下移动
export function down(index, arr) {
  if (index == arr.length - 1) {
    //结尾不移动
    return;
  }
  const curObj = arr[index]; //当前对象
  const downObj = arr[index + 1]; //下一个对象
  arr.splice(index, 1, downObj); //下一个对象移动到当前对象位置
  arr.splice(index + 1, 1, curObj); //当前对象往下移动
  return arr;
}
export const logicalOptions = [
  {
    value: 'and',
    label: '并且',
  },
  {
    value: 'or',
    label: '或者',
  },
];

//左侧新增model
export const leftAddRow = {};

//右侧新增model
export const rightAddRow = {};

export const compareOptions = [
  {
    value: '>=',
    label: '>=',
  },
  {
    value: '<=',
    label: '<=',
  },
  {
    value: '>',
    label: '>',
  },
  {
    value: '<',
    label: '<',
  },
  {
    value: '<>',
    label: '<>',
  },
  {
    value: '=',
    label: '=',
  },
];
export const compareOptions2 = [
  {
    value: '=',
    label: '=',
  },
  {
    value: '<>',
    label: '<>',
  },
];

export const fieldDisplayOptions = [
  {
    label: '显示',
    value: 'show',
  },
  {
    label: '隐藏',
    value: 'hide',
  },
];

export const itemKeys = [
  {
    label: '当前日期',
    value: '{$curDate}',
  },
  {
    label: '当前用户',
    value: '{$curUser}',
  },
  {
    label: '表单字段',
    value: 'mainFormOpt',
  },
  //   {
  //     label: '空值',
  //     value: 'null',
  //   },
];

//处理views xml
export const getviews = ({ views }) => {
  const data: any = [];
  if (views) {
    let xml;
    try {
      xml = $.parseXML(views);

      const $xml = $(xml);

      const divCount = 0;
      let count = 0;
      let rowCount = 1; // 因为默认有一行空的规则，实际在遍历中rowCount++后从2开始

      $xml
        .find('config')
        .children()
        .each(function (i) {
          // if ($(this).children().size() > 0) {
          //   // 删除ready事件中addCond中加入的第一行
          //   $('#views1').remove();
          // }
          $(this)
            .children()
            .each(function () {
              count++;
              rowCount++;
              const thenAry = $.parseJSON($(this).find('then').text());
              if (thenAry && thenAry.length > 0) {
                thenAry.forEach((item) => {
                  let val = decodeJSON(item.val).replaceAll('"', '&quot;');
                  let ary = itemKeys.filter((item) => item.value == val);
                  item['curTypeName'] = ary[0]?.label;
                  item.val = val;
                });
              }
              // let jsonLen = 0;
              // for (const key in json) {
              //   jsonLen++;
              // }

              // if (jsonLen == 0) return data;
              // const childRight: any = [];
              // for (const key in json) {
              //   childRight.push({
              //     field: key,
              //     field_display: json[key],
              //   });
              // }
              const ifAry = $.parseJSON($(this).find('if').text());
              // const conditionText = $(this).find('condition').text();
              // const fieldName = $(this).find('fieldName').text();
              // const operator = $(this).find('operator').text();
              // const val = $(this).find('value').text();
              if (ifAry && ifAry.length > 0) {
                ifAry.forEach((item) => {
                  let val = decodeJSON(item.val).replaceAll('"', '&quot;');
                  let ary = itemKeys.filter((item) => item.value == val);
                  item['curTypeName'] = ary[0]?.label;
                  item.val = val;
                });
                data.push({
                  desc: $(this).find('desc').text(),
                  childLeft: ifAry,
                  childRight: thenAry,
                });
              }
            });
        });
    } catch (e) {
      console.error('getFormParams', e);
    }
  }
  return { data };
};

//设置views xml
export const setviews = (list) => {
  let str = '';
  let isValid = true;
  let inp = '';
  const data = cloneDeep(list);
  data.forEach((item) => {
    let ifs = '';
    if (item.desc.trim() == '') {
      isValid = false;
      inp = '请输入规则名称';
      return;
    }
    if (item.childLeft && item.childLeft.length > 0) {
      item.childLeft.forEach((lt) => {
        if (!lt.field) {
          isValid = false;
          inp = '请选择如果项';
          return;
        }
        if (!lt.operator) {
          isValid = false;
          inp = '请选择判断符号';
          return;
        }
        if (lt.val) {
          // lt.val = encodeJSON(lt.val);
        } else {
          lt.val = '';
        }
        if (lt.operator) {
          lt.operator = lt.operator.replaceAll('<', '&lt;');
          lt.operator = lt.operator.replaceAll('>', '&gt;');
        } else {
          lt.operator = '';
        }
        if (ifs == '') {
          ifs +=
            '{"field":"' +
            lt.field +
            '", "operator":"' +
            lt.operator +
            '", "val":"' +
            lt.val +
            '"}';
        } else {
          ifs +=
            ', {"field":"' +
            lt.field +
            '", "operator":"' +
            lt.operator +
            '", "val":"' +
            lt.val +
            '"}';
        }
      });
    }
    if (!isValid) return { inp, isValid, views: '' };
    let displays = '';
    if (item.childRight && item.childRight.length > 0) {
      item.childRight.forEach((lt) => {
        if (!lt.field) {
          isValid = false;
          inp = '请选择结果项';
          return;
        }
        if (!lt.operator) {
          isValid = false;
          inp = '请选择结果项中的判断符号';
          return;
        }
        if (lt.val) {
          // lt.val = encodeJSON(lt.val);
        } else {
          lt.val = '';
        }
        if (lt.operator) {
          lt.operator = lt.operator.replaceAll('<', '&lt;');
          lt.operator = lt.operator.replaceAll('>', '&gt;');
        } else {
          lt.operator = '';
        }
        if (displays == '') {
          displays +=
            '{"field":"' +
            lt.field +
            '", "operator":"' +
            lt.operator +
            '", "val":"' +
            lt.val +
            '", "logical":"' +
            (lt.logical ?? '') +
            '"}';
        } else {
          displays +=
            ', {"field":"' +
            lt.field +
            '", "operator":"' +
            lt.operator +
            '", "val":"' +
            lt.val +
            '", "logical":"' +
            (lt.logical ?? '') +
            '"}';
        }
      });
    }
    // displays = '{' + displays + '}';

    str += '<rule>';

    ifs = '[' + ifs + ']';
    displays = '[' + displays + ']';
    str += '<desc>' + (item?.desc ?? '') + '</desc>';
    str += '<if>' + ifs + '</if>';
    str += '<then>' + displays + '</then>';
    str += '</rule>';
  });

  if (!isValid) return { inp, isValid, views: '' };

  // 查找internalName对应的项，如果有，则删除
  let viewsText = ''; // o("views").value; o("views").value 中如果有被转义的<>则会被恢复成<>，致xml解析出错
  if (viewsText == '') {
    viewsText = '<config></config>';
  }
  const xml = $.parseXML(viewsText);
  const $xml = $(xml);
  const isFound = false;
  $xml
    .find('config')
    .children()
    .each(function (i) {
      $(this).remove();
    });

  const $elem = $($.parseXML('<rules>' + str + '</rules>'));
  let newNode = null;
  if (typeof document.importNode == 'function') {
    newNode = document.importNode($elem.find('rules').get(0), true);
  } else {
    newNode = $elem.find('rules').get(0);
  }

  $xml.find('config').get(0).appendChild(newNode);

  return { inp, isValid, views: $xml.xml() };
};

// 对字符串中的引号进行解码
function decodeJSON(jsonString) {
  jsonString = jsonString.replace(/%dq/gi, '"');
  jsonString = jsonString.replace(/%sq/gi, "'");

  jsonString = jsonString.replace(/%lb/gi, '{');
  jsonString = jsonString.replace(/%rb/gi, '}');

  jsonString = jsonString.replace(/%eq/gi, '=');
  jsonString = jsonString.replace(/%co/gi, ',');

  // jsonString = jsonString.replace(/%rn/g, "\r\n")
  // jsonString = jsonString.replace(/%n/g, "\n")
  return jsonString;
}

function encodeJSON(jsonString) {
  jsonString = jsonString.replace(/=/gi, '%eq');
  jsonString = jsonString.replace(/\{/gi, '%lb');
  jsonString = jsonString.replace(/\}/gi, '%rb');
  jsonString = jsonString.replace(/,/gi, '%co'); // 逗号
  jsonString = jsonString.replace(/\"/gi, '%dq');
  jsonString = jsonString.replace(/'/gi, '%sq');
  jsonString = jsonString.replace(/\r\n/g, '%rn'); // 回车换行
  jsonString = jsonString.replace(/\n/g, '%n');
  return jsonString;
}
